/*
 * Created by JFormDesigner on Thu Apr 04 16:19:47 CST 2024
 */

package org.chunyan.exam.gui.setting;

import org.chunyan.exam.gui.computerinformation.ExamComputerInformationForm;

import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import javax.swing.*;
import javax.swing.text.*;

/**
 * @author Administrator
 */
public class SettingForm extends JDialog {

    private ExamComputerInformationForm owner;

    public SettingForm(Frame owner) {
        super(owner);
        this.owner = (ExamComputerInformationForm) owner;
        initComponents();
        setContentTextAreaLimit(50);
        getSettingPromptInSettingFile();
    }

    private void getSettingPromptInSettingFile(){
        String path = "exam.properties";
        File file = new File(path);
        try (Reader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {
            Properties prop = new Properties();
            prop.load(reader);
            String content =prop.getProperty("prompt");
            this.contentTextArea.setText(content);
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    private void setContentTextAreaLimit(int maxCharacters) {
        Document doc = this.contentTextArea.getDocument();
        ((AbstractDocument) doc).setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
                if (fb.getDocument().getLength() + str.length() > maxCharacters) {
                    // 如果添加新字符后的长度超过最大字符数，则不添加
                    return;
                }
                super.insertString(fb, offs, str, a);
            }

            @Override
            public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
                if (str == null) {
                    // 当删除字符时，直接允许
                    super.replace(fb, offs, length, null, a);
                } else {
                    int currentLength = fb.getDocument().getLength();
                    // 计算替换后的长度
                    int newLength = currentLength - length + str.length();
                    if (newLength > maxCharacters) {
                        // 如果替换后的长度超过最大字符数，则截断字符串
                        super.replace(fb, offs, currentLength - offs - (newLength - maxCharacters), null, a);
                    } else {
                        super.replace(fb, offs, length, str, a);
                    }
                }
            }
        });
    }

    private void savePrompt(ActionEvent e) {
        // TODO add your code here
        String path = "exam.properties";
        File file = new File(path);
        try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
            Properties prop = new Properties();
            prop.load(new FileInputStream(path));
            prop.setProperty("prompt", contentTextArea.getText());
            prop.store(writer, "exam.properties");
            JOptionPane.showConfirmDialog(this, "\u6b22\u8fce\u8bcd\u5df2\u4fdd\u5b58\u3002", "\u63d0\u793a", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
            owner.getMessageLabel().setText(prop.getProperty("prompt"));
            this.dispose();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        scrollPane1 = new JScrollPane();
        contentTextArea = new JTextArea();
        saveButton = new JButton();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        setTitle("\u81ea\u5b9a\u4e49\u6b22\u8fce\u8bcd-50\u5b57");
        setModal(true);
        Container contentPane = getContentPane();
        contentPane.setLayout(null);

        //======== scrollPane1 ========
        {
            scrollPane1.setViewportView(contentTextArea);
        }
        contentPane.add(scrollPane1);
        scrollPane1.setBounds(25, 15, 140, 50);

        //---- saveButton ----
        saveButton.setText("\u4fdd\u5b58");
        saveButton.addActionListener(e -> savePrompt(e));
        contentPane.add(saveButton);
        saveButton.setBounds(new Rectangle(new Point(55, 85), saveButton.getPreferredSize()));

        contentPane.setPreferredSize(new Dimension(190, 165));
        setSize(190, 165);
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JScrollPane scrollPane1;
    private JTextArea contentTextArea;
    private JButton saveButton;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
